package cn.colorful.olympic.util;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncImageLoader {
	
	private final String TAG = "AsyncImageLoader";
	private Map<String, SoftReference<Drawable>> imageCache=new HashMap<String, SoftReference<Drawable>>();
	
	/**
	 * 加载图标
	 * @author qianj
	 * @create 2012-4-5 下午12:13:21
	 * @since 
	 * @param imageUrl
	 * @param callback
	 * @return
	 */
	public Drawable loadDrawable(final String imageUrl,final ImageCallback callback){
		if(imageCache.containsKey(imageUrl)){
			SoftReference<Drawable> softReference=imageCache.get(imageUrl);
			if(softReference.get()!=null){
				return softReference.get();
			}
		}
		final Handler handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				callback.imageLoaded((Drawable) msg.obj, imageUrl);
			}
		};
		new Thread(){
			public void run() {
				Drawable drawable=loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				handler.sendMessage(handler.obtainMessage(0,drawable));
			};
		}.start();
		return null;
	}
	
	/**
	 * 通过URL拿图标
	 * @author qianj
	 * @create 2012-4-5 下午12:12:47
	 * @since 
	 * @param imageUrl
	 * @return
	 */
	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			URL url = new URL(imageUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			if(conn != null){
				InputStream is = url.openStream();
				Drawable d = Drawable.createFromStream(is, "src");
				conn.disconnect();
				is.close();
				return d;
			} else {
				Log.i(TAG, "地址"+imageUrl+"无图片");
				return null;
			}
		} catch (Exception e) {
			Log.i(TAG, "由URL得到图片时异常！");
			e.printStackTrace();
			//throw new RuntimeException(e);
			return null;
		}
	}

	public interface ImageCallback{
		public void imageLoaded(Drawable imageDrawable,String imageUrl);
	}
}
